// Package middleware 权限认证模块
package middleware

import (
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"net/http"
)

// AuthRequired 权限认证
func AuthRequired() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("token")
		if token == "123" { //token验证
			c.Next()
			return
		}
		if url := c.Request.URL.Path; url == "/login" { //白名单放行
			c.Next()
			return
		}
		username := GetSession(c, "username") //session验证
		if username != nil {
			c.Next()
			return
		}
		c.JSON(http.StatusUnauthorized, gin.H{
			"code": -1,
			"msg":  "权限验证失败",
		})
		c.Abort()
		return
	}
}

// SetSession 设置session
func SetSession(c *gin.Context, key string, value string) {
	session := sessions.Default(c)
	session.Set(key, value)
	session.Save()
}

// GetSession 获取session
func GetSession(c *gin.Context, key string) interface{} {
	session := sessions.Default(c)
	return session.Get(key)
}

// DelSession 删除session
func DelSession(c *gin.Context, key string) {
	session := sessions.Default(c)
	session.Delete(key)
	session.Save()
}

// ClearSession 清除session
func ClearSession(c *gin.Context) {
	session := sessions.Default(c)
	session.Clear()
	session.Save()
}
